<template>
    <fieldset>
        <legend>页面加载</legend>
        <h2>{{content}}</h2>
        <button v-for="(item,index) in btn" :key="index" @click="handleFn(index+1)" :class="{active:index+1 === who}">{{item}}</button>
    </fieldset>
</template>

<script setup>
    import {ref,reactive,onMounted,watchEffect} from 'vue'
    import CancelPromise from './cancelPromise.js'
    let btn = reactive(['第1页','第2页','第3页'])
    let who = ref(1)
    let handleFn=(index)=>{
        //修改who的值
        who.value = index
        //获取接口数据
        // getData(index)
    }
    let api1 = signal=>new CancelPromise((resolve,reject)=>{
        setTimeout(() => {
            resolve('这是FirstPage数据');
        }, 1000)
    },signal)
    let api2 = signal=>new CancelPromise((resolve,reject)=>{
        setTimeout(() => {
            resolve('这是第SecondPage数据');
        }, 1500)
    },signal)
    let api3 = signal=>new CancelPromise((resolve,reject)=>{
        setTimeout(() => {
            resolve('这是ThirdPage数据');
        }, 2000)
    },signal)
    let api = {
        api1,
        api2,
        api3
    }
    //定义一个获取数据的方法
    let getData = (i=1,signal)=>(
        api['api'+ i](signal)
        .then(res=>{
            console.log(res);
            content.value = res
        })
    )
    //接受获取到的数据
    let content = ref(1)
    // //页面加载时默认获取第一页数据
    // onMounted(()=>{
    //     getData(1)
    // })

    watchEffect(invalidate=>{
        //声明控制器
        let abortController = new AbortController();
        //获取signal对象
        let signal = abortController.signal;
        //发起请求,传入signal对象
        getData(who.value,signal)
        invalidate(()=>{
            //页面切换之前 取消上一个promise
            abortController.abort()
        })
    })
</script>

<style scoped>
    .active{
        background-color: darkgoldenrod;
    }
</style>